package com.margo.project.socket.post;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 相比于GET请求，POST报文多了如下几个要素：
 * 1，Content-Length，这个是上送报文的长度，以字节为单位
 * 2，Content-Type，这主要是涉及到报文的格式和字符集。
 * 3，就是主报文
 * socket模拟http post请求
 * @author fxb208
 *
 */
public class SocketPostClient {
	public static void main(String[] args) {
		/**
		 * 返回的http报文
		 * 
		 * HTTP/1.1 200 
		 * Content-Type: application/json;charset=UTF-8
		 * Content-Length: 2
		 * Date: Wed, 07 Nov 2018 01:15:42 GMT
		 * 
		 * ok
		 * 
		 */
		try {
		    String host = "localhost";
		    int port = 8080;
		    Socket socket = new Socket();
		    InetSocketAddress address=new InetSocketAddress(host, port);
		    socket.connect(address,10000); 
		    OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"utf-8");
		    //请求行
		    osw.write("POST /iep/mobile/mobileservice/fileAction/upByteFile.iep HTTP/1.1\r\n");
		    //请求头
		    osw.write("Accept: application/json\r\n");
		    osw.write("Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n");
		    osw.write("Content-Length: 5\r\n");
		    osw.write("Host: 127.0.0.1:8080\r\n");
		    osw.write("Connection: Keep-Alive\r\n");
		    osw.write("User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_171)\r\n");
		    osw.write("Accept-Encoding: gzip,deflate\r\n");
		    //http协议必须在报文头后面再加一个换行，通知服务器发送完成，不然服务器会一直等待
		    osw.write("\r\n");
		    //请求数据
		    osw.write("margo\r\n");
		    osw.write("\r\n");
		    osw.flush();
		    socket.shutdownOutput();
		    BufferedReader bufferedReader = new BufferedReader(
		            new InputStreamReader(socket.getInputStream(), "utf-8"));
		    String line = null;
		    while ((line = bufferedReader.readLine()) != null) {
		        System.out.println(line);
		    }
		    osw.close();
		    bufferedReader.close();
		    socket.close();		
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
